package propcalc_lang.ast;

import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * Bicondicional (si y sólo si) entre dos proposiciones.
 * 
 * @author Leonardo Val.
 */
public class Biconditional extends Proposition {
	public final Proposition operand1, operand2;

	public Biconditional(Proposition operand1, Proposition operand2) {
		this.operand1 = operand1;
		this.operand2 = operand2;
	}

	@Override
	public String unparse() {
		return "(" + operand1.unparse() + " <-> " + operand2.unparse() + ")";
	}

	public static Biconditional generate(Random random, int min, int max) {
		return new Biconditional(
				Proposition.generate(random, min - 1, max - 1),
				Proposition.generate(random, min - 1, max - 1));
	}

	@Override
	public Set<String> variables(Set<String> vars) {
		this.operand1.variables(vars);
		this.operand2.variables(vars);
		return vars;
	}

	@Override
	public Proposition substitution(Map<String, Proposition> replacements) {
		Proposition p1 = this.operand1.substitution(replacements);
		Proposition p2 = this.operand2.substitution(replacements);

		return new Biconditional(p1, p2);
	}

	@Override
	public boolean match(Proposition pattern,
			Map<String, Proposition> replacements) {
		if (pattern instanceof Variable) {
			Variable var = (Variable) pattern;
			if (replacements.containsKey(var.identifier)) {
				return this.equals(replacements.get(var.identifier));
			} else {
				replacements.put(var.identifier, this);
				return true;
			}
		} else {
			if (pattern instanceof Biconditional) {
				Biconditional bic = (Biconditional) pattern;
				return this.operand1.match(bic.operand1, replacements)
						&& this.operand2.match(bic.operand2, replacements);

			}
		}
		return false;
	}

	@Override
	public String toString() {
		return "Biconditional(" + operand1 + ", " + operand2 + ")";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((operand1 == null) ? 0 : operand1.hashCode());
		result = prime * result
				+ ((operand2 == null) ? 0 : operand2.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Biconditional other = (Biconditional) obj;
		if (operand1 == null) {
			if (other.operand1 != null)
				return false;
		} else if (!operand1.equals(other.operand1))
			return false;
		if (operand2 == null) {
			if (other.operand2 != null)
				return false;
		} else if (!operand2.equals(other.operand2))
			return false;
		return true;
	}

}
